package net.bwie.realtime.jtp.dws.log.function;

import net.bwie.realtime.jtp.dws.log.bean.PageViewBean;
import net.bwie.realtime.jtp.utils.DateTimeUtil;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class PageViewReportwindowFunction implements WindowFunction<PageViewBean, String, String, TimeWindow> {
    @Override
    public void apply(String key, TimeWindow window, Iterable<PageViewBean> input, Collector<String> out) throws Exception {
        /*
          key：表示分组：window：表示时间窗口，可以获取窗口开始和结束时间：input，表示窗口中所有数据
         */

        // 1.获取窗口开始和结束时间
        String windowStart = DateTimeUtil.convertLongToString(window.getStart(), "yyyy-MM-dd HH:mm:ss");
        String windowEnd = DateTimeUtil.convertLongToString(window.getEnd(), "yyyy-MM-dd HH:mm:ss");

        // 2.对窗口中数据计算
        PageViewBean bean = input.iterator().next();
        Long pvCount = bean.getPvCount();
        Long pvDuringTime = bean.getPvDuringTime();
        Long uvCount = bean.getUvCount();
        Long sessionCount = bean.getSessionCount();

        // 3.输出数据
        String output = windowStart + "," + windowEnd + ","
                + windowStart.substring(0,10) + ","
                + key + "," + uvCount + "," + sessionCount + "," + pvCount + "," + pvDuringTime;
        out.collect(output);
    }
}
